<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="servlets.message.*"%>
<%@ page import="org.hibernate.SessionFactory"%>
<%@ page import="org.hibernate.Session"%>
<%@ page import="java.util.List"%>
<%@ page import="hibernate.model.*"%>
<%@ page import="hibernate.util.HibernateUtil"%>
<%@ page import="hibernate.method.*"%>
<%@ page import="hibernate.method.UserMethods"%>

<script>

$(".subjects").click(function(e){
	 e.preventDefault();
	 var clickedID = $(this).attr('id');
	  $.ajax({
	       url: "../MessageDetails",
	       type: "POST",
	       data: {
		       messageID: clickedID
	       },
	       dataType: 'json',
	       success: function (json) {
			var data = json;
			$("#msg").hide().fadeIn(1000).html("<table class=\"table\">");
		    $("#msg").append("<tr><td>Nadawca:</td><td>"+data.sender+"</td></tr>");
		    $("#msg").append("<tr><td>Data:</td><td>"+data.date+"</td></tr>");
		    $("#msg").append("<tr><td>Godzina:</td><td>"+data.time+"</td></tr>");
		    $("#msg").append("<tr><td>Temat:</td><td>"+data.subject+"</td></tr>");
		    $("#msg").append("<tr><td>Tresc:</td><td>"+data.content+"</td></tr>");
		    $("#msg").append("</table>");
	       },
	       error: function(xhr, ajaxOptions, thrownError){
	       },
	       timeout : 15000
	  });

	});

</script>

<script>
$(document).ready(function() {
	
$('#receiver').change(function(event) {
        var receiver_id = $("select#receiver").val();
        $.post('../RetrieveMsgByReceiver', {
                receiver_id : receiver_id
        },  function(response) {
        	$('.table-responsive').html("");
            console.log(response);
            if (response.length == 0)
            	$('.table-responsive').append("Brak wiadomosci w skrzynce odbiorczej");
            else { 
            	var html= "<table class=\"table\">";
            	html += "<thead><tr><td>Nadawca</td><td>Temat </td><td>Data</td><td> Usuń </td></tr></thead><tbody>";
              $.each(response, function(index, value) {
                  console.log(value);
                  if (value.trim() != ""){
            	  $.ajax({
           	       url: "../MessageDetails",
           	       type: "POST",//type of posting the data
           	       data: {
           	    	messageID: value
           	       },
           	       dataType: 'json',
           	       success: function (json) {
           			var data = json;
           			console.log(data);

           			html +="<tr>";
           			html +="<td>" + json.sender +"</td>";
           			html += "<td><a class=\"subjects\" id=\""+ json.message_id + "\" href=\"#\">" + json.subject + "</a>"+"</td>";
           			html +="<td>" + json.date + " " + "godz. " +  json.time+ "</td>";
           			html +="<td>";
           			html += "<form action=\"../DeleteMessage\" method=\"POST\" name='formularz'>";
           			html += "<input type=\"hidden\" id=\"message_id\" name=\"message_id\" value=\""+ json.message_id + "\" /> ";
               		html += "<input type=\"submit\" class=\"mainBtn\" value=\"Usuń\" />";
               		html += "</form>";
					html +="</td>";
					html +="</tr>";
           			

           		 $('.table-responsive').append(html);
           	    },
     	       error: function(xhr, ajaxOptions, thrownError){
     	       },
     	       timeout : 15000
     	  });
                  }
              });
             
              console.log(html);
              $('.table-responsive').append("</tbody></table>");
              
            }

        }); 
});
});
</script>


<%
						SessionFactory sessionFactory = HibernateUtil
								.getSessionAnnotationFactory();
						Session s = sessionFactory.openSession();
						s.beginTransaction();
						UserMethods u_m = new UserMethods();
						List<User> ulist = u_m.list(sessionFactory, s);
					
						
					%> 
	
<div class="page-header">
	<h2 class="page-title">Skrzynka odbiorcza<br>
	- Wyswietl jako: 
	<select id="receiver" name="receiver" >
						<%		if (ulist.size() > 0) {
							
							for (User u1 : ulist) {
								if (u1==u_m.id_to_user(sessionFactory, s, (Integer) session.getAttribute("user_id"))) 
								{
									int toRemove=ulist.indexOf(u1);
								%>	<option value="<%=(Integer) session.getAttribute("user_id")%>" selected><%out.print("ja"); %>
								<%
								if(ulist.size()==1) out.println ("Nie ma uzytkownikow do ktorych moglbys napisac");
								}
								else {
								String username = u1.getUsername();
								String usertype="";
								if ("worker".equals(u1.getType())) usertype="[obsługa]";
								if ("admin".equals(u1.getType())) usertype="[administracja]";
								int id = u1.getUser_id();%>
						<option value="<%=id%>"><%out.print(username+" "+usertype);%></option>
						<%}
							}
							
						}
						if (ulist.size() == 0) {
					out.println("Nie ma zadnych uzytkownikow w bazie");
						} %>
						</select> 
	
	</h2>
</div>

<br />

<div id="content">
<%
						MessageMethods msg_m = new MessageMethods();
						 Integer user_id = (Integer) session.getAttribute("user_id");
							response.setContentType("text/html");
							if (user_id != null) {
						List<Message> msglist = msg_m.list_by_receiver(sessionFactory, s, user_id);
					%> 
	
<div class="table-responsive">			
<%if (msglist.size() > 0) {%>
<table class="table" id="send_table">
<thead>
<tr>
<td>Nadawca</td>
<td>Temat </td>
<td>Data</td>
</tr>
</thead>
<%
	for (Message m1 : msglist) {
		int sender_id = m1.getSender_id();
		User sender = u_m.id_to_user(sessionFactory, s, sender_id);
		String sender_nick = sender.getUsername();
		String subject = m1.getSubject();
		String date = m1.getSend_date();
		String time = m1.getSend_time();
		%>
		<tbody>
<tr>
<td><% out.println(sender_nick); %></td>
<td><% out.println("<a class=\"subjects\" id=\""+ m1.getMessage_id() + "\" href=\"#\">" + subject + "</a>"); %> </td>
<td><% out.println(date + " " + "godz. " +  time); %></td>
</tr>
</tbody>		
		<%
		}
		}
else out.println("Brak wiadomosci w skrzynce odbiorczej");
		}
							s.getTransaction().commit();
		%>
		
		
		

</table>
</div>

<br > <br> <br>
<br/><br />
</div>
<div id="messageDetails">
<div class="page-header">
<h2 class="page-title">Szczególy wiadomosci</h2>
</div>
<div id="msg">Kliknij na temat wiadomosci, której szczegoly chcesz zobaczyc</div>
</div>

    <link href="../admin/main/assets/css/main.css" rel="stylesheet">